package com.wjs.readwrite;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

class Mycache{
    private volatile Map<String,Object> map=new HashMap<>();
    //创建读写锁对象
    private ReadWriteLock rwlock=new ReentrantReadWriteLock();
    //放数据
    public void put(String key,Object value){
        rwlock.writeLock().lock();
        try {
            System.out.println(Thread.currentThread().getName()+"正在写操作"+key);
            TimeUnit.MILLISECONDS.sleep(300);
            map.put(key,value);
            System.out.println(Thread.currentThread().getName()+"写完了"+key);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            rwlock.writeLock().unlock();
        }
    }
    public Object get(String key){
        rwlock.readLock().lock();
        Object result=null;
        try {
            System.out.println(Thread.currentThread().getName()+"正在读操作"+key);
            TimeUnit.MILLISECONDS.sleep(300);
           result = map.get(key);
            System.out.println(Thread.currentThread().getName()+"取完了"+key);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            rwlock.readLock().unlock();
        }
        return result;
    }
}
public class ReadWirteLockDemo {
    public static void main(String[] args) {
        Mycache mycache = new Mycache();
        for (int i = 1; i <= 5; i++) {
            final int num=i;
            new Thread(()->{
                mycache.put(num+"",num+"");
            },String.valueOf(i)).start();
        }

        for (int i = 1; i <= 5; i++) {
            final int num=i;
            new Thread(()->{
                mycache.get(num+"");
            },String.valueOf(i)).start();
        }
    }
}
